package com.app.web.order;

import com.app.base.EnumType;
import com.app.utils.base.http.ResultUtil;
import com.app.utils.base.j2se.Common;
import com.app.utils.base.j2se.Convert;
import com.app.utils.base.j2se.StringHandler;
import com.app.utils.spring.properties.Config;
import com.app.utils.web.Param;
import com.app.web.goods.goods.GoodsService;
import com.app.web.order.job.OrderPromotionDetails;
import com.app.web.user.info.UserInfo;
import com.app.web.user.info.UserInfoService;
import com.app.web.user.login.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: tbyy-app->OrderController
 * @Auther: 王伟
 * @Date: 2019/12/13 15:16
 * @Description: 订单
 */
@RestController
@RequestMapping("/order/")
public class OrderController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private OrderPromotionDetails orderPromotionDetails;

    @RequestMapping("promotion")
    public void promotion(){
        orderPromotionDetails.analy();
    }

    /**
     *  购买
     * @param uid
     * @param address_id 快递地址id
     * @param goods_id  商品id
     * @param num   购买数量
     * @param units 商品规格
     * @param money 购买总金额
     * @return
     */
    @RequestMapping("pay")
    public String pay(@RequestAttribute long uid,int address_id,int goods_id,int num,String units,int money,
                      @RequestParam(defaultValue = "1")int type ,@RequestParam(defaultValue = "1") int payChannel){
        if (StringHandler.getInt(Config.pp.get("ys.goods.pay.switch"),1)==0) {
            return ResultUtil.error(6001, "该功能研发中...");
        }
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            return ResultUtil.error(6001, "交易系统已关闭");
        }
        UserInfo userInfo = userInfoService.info(uid);
        if(Common.isEmpty(userInfo)){
            return ResultUtil.error(6001,"参数异常，请下载最新版本APP");
        }
        if(address_id==0){
            return ResultUtil.error(6001,"请选择收货地址");
        }
        Map<String,Object> goods = goodsService.goods(goods_id,userInfo.getRole());
        if(Common.isNotEmpty(goods.get("units")) && Common.isEmpty(units)){
            return ResultUtil.error(6001,"请选择商品规格");
        }
        int price = Convert.objToInt(goods.get("inner_price"));
        if(money != price*num){
            return ResultUtil.error(6001,"商品金额异常，请联系客服");
        }
        if(num > Convert.objToInt(goods.get("inventory"))){
            return ResultUtil.error(6001,"商品库存不足，请联系客服");
        }
        // 1 在线支付 2 钱包支付 3 支付宝
        long orderId = orderService.order(type,userInfo,goods,num,units,money,address_id,payChannel);
        return ResultUtil.success(orderId);
    }


    /**
     *  购买
     * @param uid
     * @param address_id 快递地址id
     * @param goods_id  商品id
     * @param num   购买数量
     * @param units 商品规格
     * @param money 购买总金额
     * @return
     */
    @RequestMapping("pays")
    public String pays(@RequestAttribute long uid,int address_id,String goods_id,String num,String units,int money,int type){
        if (StringHandler.getInt(Config.pp.get("ys.goods.pay.switch"),1)==0) {
            return ResultUtil.error(6001, "该功能研发中...");
        }
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            return ResultUtil.error(6001, "交易系统已关闭");
        }
        UserInfo userInfo = userInfoService.info(uid);
        if(Common.isEmpty(userInfo)){
            return ResultUtil.error(6001,"参数异常，请下载最新版本APP");
        }
        if(address_id==0){
            return ResultUtil.error(6001,"请选择收货地址");
        }
        List<Integer> goodsIds = Arrays.stream(goods_id.split(",")).map(Convert::objToInt).collect(Collectors.toList());
        List<Integer> nums = Arrays.stream(num.split(",")).map(Convert::objToInt).collect(Collectors.toList());
        List<String>  unitss =  Arrays.stream(units.split(",")).collect(Collectors.toList());

        List<Long> orderIds = new ArrayList<>();
        int payChannel = 1;
        if("mb".equals(StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys"))){
            payChannel = 2;
        }

        for (int i = 0; i < goodsIds.size(); i++) {
            Map<String,Object> goods = goodsService.goods(goodsIds.get(i),userInfo.getRole());
            if(Common.isNotEmpty(goods.get("units")) && Common.isEmpty(unitss.get(i))){
                return ResultUtil.error(6001,"请选择商品规格");
            }
            int price = Convert.objToInt(goods.get("inner_price"));
            if(money != price*nums.get(i)){
                return ResultUtil.error(6001,"商品金额异常，请联系客服");
            }
            if(nums.get(i) > Convert.objToInt(goods.get("inventory"))){
                return ResultUtil.error(6001,"商品库存不足，请联系客服");
            }
            //type 1 在线支付 2 钱包支付
            long orderId = orderService.order(type,userInfo,goods,nums.get(i),unitss.get(i),money,address_id,payChannel);
            orderIds.add(orderId);
        }

        return ResultUtil.success(orderIds.toString());
    }

    /**
     * 确认收货
     * @param order_sn
     * @return
     */
    @RequestMapping("confirmReceipt")
    public String confirmReceipt(@RequestAttribute long uid,String order_sn){
        orderService.orderChange(order_sn);
        return ResultUtil.success();
    }

    /**
     * 订单信息查询，用于退货退款
     * @param order_sn
     * @return
     */
    @RequestMapping("cancelOrder")
    public String cancelOrder(@RequestAttribute long uid,String order_sn){
        return ResultUtil.success(orderService.getOrder(order_sn));
    }

    /**
     * 退货申请
     * @param uid
     * @param order_sn
     * @param reason
     * @return
     */
    @RequestMapping("cancelApply")
    public String cancelApply(@RequestAttribute long uid,int order_status,String order_sn,String reason){
        orderService.cancelApply(uid,order_status, order_sn, reason);
        return ResultUtil.success();
    }

    /**
     * 填写退货信息
     * @param uid
     * @param order_sn
     * @param express_name
     * @param express_no
     * @return
     */
    @RequestMapping("cancel")
    public String cancel(@RequestAttribute long uid,String order_sn,String express_name,String express_no){
        orderService.cancel(uid, order_sn, express_name, express_no);
        return ResultUtil.success();
    }

    /**
     * 我的订单列表
     * @param uid
     * @param status
     * @param page
     * @return
     */
    @RequestMapping("getUidOrderList")
    public String getUidOrderList(@RequestAttribute long uid,
                                  @RequestParam(defaultValue = "0") int status,
                                  @RequestParam(defaultValue = "1") int page){
        List<Map<String,Object>> orderList = orderService.orderListByUid(uid,status,page);
        if(Common.isEmpty(orderList)){
            return ResultUtil.success(new ArrayList<>());
        }
        orderList = orderList.stream().map(x -> {
            if(Common.isNotEmpty(x.get("create_time"))){
                x.put("order_create_time",Convert.objToStr(x.get("create_time")).substring(0,19));
            }
            int order_status = Convert.objToInt(x.get("order_status"));
            String status_name = EnumType.ORDER_STATUS.getName(order_status);
            String status_color = EnumType.ORDER_STATUS.getColor(order_status);
            x.put("status_color",status_color);
            x.put("status_name",status_name);
            String pic = Convert.objToStr(x.get("goods_pic"));
            int source = StringHandler.getInt(x.get("source"));
            x.put("source_name",source==1?"直营":"聚水潭");
            if(source==1) {
                if (!pic.startsWith("http")) {
                    x.put("goods_pic", Param.picUrl + pic);
                }
            }
            if(source==2){
                x.put("order_amount",StringHandler.fenToYuan(x.get("order_amount")+""));
            }
            return x;
        }).collect(Collectors.toList());
        return ResultUtil.success(orderList);
    }
    /**
     * 收益订单列表
     * @param uid
     * @param status
     * @param page
     * @return
     */
    @RequestMapping("/getOrderList")
    public String getOrderList(@RequestAttribute long uid,
                               @RequestParam(defaultValue = "1") int status,
                               @RequestParam(defaultValue = "1") int page){
        UserInfo userInfo = userInfoService.info(uid);
        /* 游客查询订单列表 */
        if(userInfo.getRole()==0){
            return ResultUtil.success();
        }
        List<Map<String,Object>> orderList = orderService.getOrderList(uid,status,page);
        if(Common.isEmpty(orderList)){
            return ResultUtil.success(0,"暂无数据");
        }
        orderList = orderList.stream().map(x -> {
            if(Common.isNotEmpty(x.get("order_create_time"))){
                x.put("order_create_time",Convert.objToStr(x.get("order_create_time")).substring(0,19));
            }
            int order_status = Convert.objToInt(x.get("order_status"));
            String status_name = EnumType.ORDER_STATUS.getName(order_status);
            String status_color = EnumType.ORDER_STATUS.getColor(order_status);
            x.put("status_color",status_color);
            x.put("status_name",status_name);
            int source = StringHandler.getInt(x.get("source"));
            x.put("source_name",source==1?"直营":"聚水潭");
            if(source==1) {
                String pic = Convert.objToStr(x.get("goods_pic"));
                if (!pic.startsWith("http")) {
                    x.put("goods_pic", Param.picUrl + pic);
                }
            }
            if(source==2){
                x.put("order_amount",StringHandler.fenToYuan(x.get("order_amount")+""));
            }
            return x;
        }).collect(Collectors.toList());

        return ResultUtil.success(orderList);
    }
}
